<?php

namespace App\Http\Controllers\Port;

use App\Models\AccessNum;
use App\Models\Activity;
use App\Models\ActivityApply;
use App\Models\Banner;
use App\Models\CompetiteActivity;
use App\Models\CompetiteActivityDatabase;
use App\Models\CompetiteActivityWorks;
use App\Models\ReadingTask;
use App\Models\ReadingTaskExecute;
use Illuminate\Support\Facades\Cache;


/**
 * web端首页
 */
class IndexController extends CommonController
{


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 第一次验证邀请码是否正确  （空方法，可不要任何代码，因为在中间件已经验证）
     * invite_code 
     */
    public function checkInviteCode()
    {
        return $this->returnApi(200, '获取成功', true);
    }




    /**
     * 官网首页
     * token 可有可无
     */
    public function index()
    {
        //获取缓存数据
        $user_id = request()->user_info['id'];
        $cache_key = md5('index_data');
        $data = Cache::get($cache_key);
        if ($data) {
            return $this->returnApi(200, '获取成功', true, $data);
        }

        //猜你喜欢
        $guess_like = $this->guessLikeInfo($user_id);
        $data['guess_like'] = $guess_like;

        //banner图片
        $banner = Banner::getBannerList(1);
        // if (empty($banner)) {
        //     $banner[0]['img'] = 'default/default_banner.png';
        //     $banner[0]['link'] = '';
        //     $banner[0]['name'] = '默认图片';
        // }
        $data['banner'] = $banner;
        //活动
        $activityModel = new Activity();
        $data['activity'] = $activityModel->getActListByTime(date('Y-m-01'), date('Y-m-d'));
        foreach ($data['activity'] as $key => $val) {
            $data['activity'][$key]['start_time'] = date('Y-m-d H:i', strtotime($val['start_time']));
            $data['activity'][$key]['end_time'] = date('Y-m-d H:i', strtotime($val['end_time']));
        }

        // //大赛
        $competiteActivityModel = new CompetiteActivity();
        $competite_activity = $competiteActivityModel->lists([
            'id', 'type_id', 'title', 'app_img as img', 'con_start_time', 'con_end_time', 'browse_num', 'intro', 'appraise_way', 'vote_start_time', 'vote_end_time'
        ], null, null, null, null, null, null, 1, 2);
        $data['competite_activity'] = $competite_activity['data'];
        foreach ($data['competite_activity'] as $key => $val) {
            $data['competite_activity'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro'])); //获取活动简介
            $data['competite_activity'][$key]['status'] = $competiteActivityModel->getCompetiteStatus($val); //获取活动状态

            $data['competite_activity'][$key]['con_start_time'] = $val['con_start_time'] ? date('Y-m-d H:i', strtotime($val['con_start_time'])) : null;
            $data['competite_activity'][$key]['con_end_time'] = $val['con_end_time'] ? date('Y-m-d H:i', strtotime($val['con_end_time'])) : null;
            $data['competite_activity'][$key]['vote_start_time'] = $val['vote_start_time'] ? date('Y-m-d H:i', strtotime($val['vote_start_time'])) : null;
            $data['competite_activity'][$key]['vote_end_time'] = $val['vote_end_time'] ? date('Y-m-d H:i', strtotime($val['vote_end_time'])) : null;

            $data['competite_activity'][$key]['type_name'] = isset($val['con_type']['type_name']) ? $val['con_type']['type_name'] : '';
            unset($data['competite_activity'][$key]['con_type']);
        }

        //数据库
        $competiteActivityDatabaseModel = new CompetiteActivityDatabase();
        $competite_activity_database = $competiteActivityDatabaseModel->lists(['id', 'name', 'img'], null, 1, null, null, 5);
        $data['competite_activity_database'] = $competite_activity_database['data'];

        //获取我的阅读任务
        if ($user_id) {
            $field = ['id', 'title', 'img', 'start_time', 'end_time', 'browse_num', 'intro', 'create_time'];
            $readingTaskModel = new ReadingTask();
            $reading_task = $readingTaskModel->lists($field, null, $user_id, 1, null, null, null, null, 1);
            //判断是否有新的阅读任务
            $readingTaskExecuteModel = new ReadingTaskExecute();
            $total_reading_task = [];
            foreach ($reading_task['data'] as $key => $val) {
                $reading_task['data'][$key]['intro'] =  str_replace('&nbsp;', '', strip_tags($val['intro']));
                $reading_task['data'][$key]['status'] = $readingTaskModel->getReadingTaskStatus($val['id']); //阅读任务状态
                $progress = $readingTaskExecuteModel->where('user_id', $user_id)->where('task_id', $val['id'])->value('progress');
                if ($progress != 100 || $progress !== '100.00') {
                    $total_reading_task[] = $val;
                }
            }
            $data['reading_task'] = $total_reading_task;
        } else {


            $data['reading_task'] = [];
        }

        Cache::put($cache_key, $data, 60); //缓存一分钟

        //添加访问量
        $accessNumObj = new AccessNum();
        $accessNumObj->add(2);

        return $this->returnApi(200, '获取成功', true, $data);
    }


    /**
     * 获取猜你喜欢的活动或征集大赛
     * @param user_id
     */
    public function guessLikeInfo($user_id)
    {
        $data = [];
        $activityApplyModel = new ActivityApply();
        $activity_type = $activityApplyModel->userApplyTypeStatistics($user_id);
        $activityModel = new Activity();
        if (!empty($activity_type[0]['type_id'])) {
            //获取当前类型下的活动
             $res = $activityModel->getActivityByTypeId($activity_type[0]['type_id']);
           if(!empty($res))   $data[] = $res[0];
        }
        if (!empty($activity_type[1]['type_id'])) {
            $res = $activityModel->getActivityByTypeId($activity_type[1]['type_id']);
            if(!empty($res))   $data[] = $res[0];
        }
        $competiteActivityWorksModel = new CompetiteActivityWorks();
        $competite_activity_type = $competiteActivityWorksModel->userApplyTypeStatistics($user_id);
        $competiteActivityModel = new CompetiteActivity();
        if (!empty($competite_activity_type[0]['type_id'])) {
            //获取当前类型下的活动
            $res = $competiteActivityModel->getCompetiteActivityByTypeId($competite_activity_type[0]['type_id']);
            if(!empty($res))   $data[] = $res[0];
        }
        if (!empty($competite_activity_type[1]['type_id'])) {
            //获取当前类型下的活动
            $res = $competiteActivityModel->getCompetiteActivityByTypeId($competite_activity_type[1]['type_id']);
            if(!empty($res))   $data[] = $res[0];
        }
        return $data;
    }


    /**
     * 根据地址转经纬度、或根据经纬度转换地址
     * @param lon  经度   经纬度 必须同时存在
     * @param lat  纬度
     * @param province 省
     * @param city 市
     * @param district 区、县
     * @param address 补充地址
     */
    public function getAddressOrLonLat()
    {
        $lon = $this->request->lon;
        $lat = $this->request->lat;
        $province = $this->request->province;
        $city = $this->request->city;
        $district = $this->request->district;
        $address = $this->request->address;

        if ((empty($lon) || empty($lat)) && (empty($city))) {
            return $this->returnApi(201, '参数错误');
        }

        if (!empty($lon) && !empty($lat)) {
            //根据经纬度获取地址
            $map = $this->getAddressByLonLat($lon, $lat);

            if (is_string($map)) return $this->returnApi(202, $map);
            $data['province']      = $map['province'];
            $data['city']          = !empty($map['city']) ? $map['city'] : $map['province'];
            $data['district']      = $map['district'];
            $data['address']       = $map['remark'];
        } else {
            $address = $province . $city . $district . $address;
            $map = $this->getLonLatByAddress($address);
            if (is_string($map)) return $this->returnApi(202, $map);
            $data['lon']                = $map['lon'];
            $data['lat']                = $map['lat'];
        }

        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 查询正在进行中的活动
     */
    public function getUnderWay()
    {
        $acticityModel = new Activity();
        $competiteActivityModel = new CompetiteActivity();
        $competite_activity_list = $competiteActivityModel->getUnderWay();
        $data = [];
        $i = 0;
        $limit = 2;
        if ($competite_activity_list) {
            foreach ($competite_activity_list as $key => $val) {
                $data[$i]['type'] = 2; //代表大赛
                $data[$i]['id'] = $val['id'];
                $data[$i]['img'] = $val['app_img'];
                $data[$i]['browse_num'] = $val['browse_num'];
                $data[$i]['title'] = $val['title'];
                $data[$i]['start_time'] = $val['con_start_time'];
                $data[$i]['end_time'] = $val['con_end_time'];
                $data[$i]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
                $data[$i]['status'] = $competiteActivityModel->getCompetiteStatus($val);
                $i++;
            }
            $limit = 1;
        }

        $activity_list = $acticityModel->getUnderWay($limit);
        if ($activity_list) {
            foreach ($activity_list as $key => $val) {
                $data[$i]['type'] = 1; //代表活动
                $data[$i]['id'] = $val['id'];
                $data[$i]['img'] = $val['img'];
                $data[$i]['browse_num'] = $val['browse_num'];
                $data[$i]['title'] = $val['title'];
                $data[$i]['start_time'] = $val['start_time'];
                $data[$i]['end_time'] = $val['end_time'];
                $data[$i]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
                $data[$i]['status'] = $acticityModel->getActListState($val);
                $i++;
            }
        }
    }

    /**
     * 查询即将开始的活动
     */
    public function getBeAboutToStart()
    {
        $acticityModel = new Activity();
        $competiteActivityModel = new CompetiteActivity();
        $competite_activity_list = $competiteActivityModel->getBeAboutToStart(2);
        $data = [];
        $i = 0;
        $limit = 3;
        if ($competite_activity_list) {
            foreach ($competite_activity_list as $key => $val) {
                $data[$i]['type'] = 2; //代表大赛
                $data[$i]['id'] = $val['id'];
                $data[$i]['img'] = $val['app_img'];
                $data[$i]['browse_num'] = $val['browse_num'];
                $data[$i]['title'] = $val['title'];
                $data[$i]['start_time'] = $val['con_start_time'];
                $data[$i]['end_time'] = $val['con_end_time'];
                $data[$i]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
                $data[$i]['status'] = $competiteActivityModel->getCompetiteStatus($val);
                $i++;
            }
            $limit = count($competite_activity_list) == 2 ? 1 : 2; //获取个数，如果有2个就获取1个，有1个就获取2个
        }

        $activity_list = $acticityModel->getBeAboutToStart($limit);
        if ($activity_list) {
            foreach ($activity_list as $key => $val) {
                $data[$i]['type'] = 1; //代表活动
                $data[$i]['id'] = $val['id'];
                $data[$i]['img'] = $val['img'];
                $data[$i]['browse_num'] = $val['browse_num'];
                $data[$i]['title'] = $val['title'];
                $data[$i]['start_time'] = $val['start_time'];
                $data[$i]['end_time'] = $val['end_time'];
                $data[$i]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
                $data[$i]['status'] = $acticityModel->getActListState($val);
                $i++;
            }
        }
    }
}
